const { Sequelize } = require('sequelize');
const fs = require('fs');
const path = require('path');
const { sequelize } = require('../config/database');

// 更新数据库函数
async function updateDatabase() {
  try {
    console.log('正在更新数据库结构...');
    
    // 读取 SQL 更新脚本
    const sqlFilePath = path.join(__dirname, '../sql/warnings.sql');
    const sqlQueries = fs.readFileSync(sqlFilePath, 'utf-8')
      .split(';')
      .filter(query => query.trim().length > 0);
    
    // 执行 SQL 更新
    let successCount = 0;
    let errorCount = 0;
    
    for (const query of sqlQueries) {
      try {
        await sequelize.query(query + ';');
        successCount++;
      } catch (error) {
        errorCount++;
        // 检查是否是"列已存在"错误
        const isColumnExistsError = error.message.includes('Duplicate column name') || 
                                    error.message.includes('already exists');
        
        if (isColumnExistsError) {
          console.log(`注意: 列已存在，跳过: ${query.trim().substring(0, 100)}...`);
        } else {
          console.error(`SQL 错误: ${error.message}`);
          console.error(`出错的 SQL: ${query}`);
        }
      }
    }
    
    console.log(`数据库结构更新完成: ${successCount} 个操作成功，${errorCount} 个操作失败（可能是列已存在）`);
    process.exit(0);
  } catch (error) {
    console.error('数据库更新失败:', error);
    process.exit(1);
  }
}

// 执行更新
updateDatabase(); 